package cn.youqu.happy.module.youqu.service.userActivity;

import cn.youqu.happy.framework.common.pojo.PageResult;
import cn.youqu.happy.framework.common.util.collection.ArrayUtils;
import cn.youqu.happy.framework.common.util.string.StrUtils;
import cn.youqu.happy.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.youqu.happy.module.member.dal.dataobject.user.MemberUserDO;
import cn.youqu.happy.module.member.service.user.MemberUserService;
import cn.youqu.happy.module.youqu.controller.admin.userActivity.vo.UserActivityCreateReqVO;
import cn.youqu.happy.module.youqu.controller.admin.userActivity.vo.UserActivityExportReqVO;
import cn.youqu.happy.module.youqu.controller.admin.userActivity.vo.UserActivityPageReqVO;
import cn.youqu.happy.module.youqu.controller.admin.userActivity.vo.UserActivityUpdateReqVO;
import cn.youqu.happy.module.youqu.controller.admin.userArrange.vo.UserArrangeCreateReqVO;
import cn.youqu.happy.module.youqu.controller.app.userActivity.vo.AppUserActivityCreateReqVO;
import cn.youqu.happy.module.youqu.controller.app.userActivity.vo.AppUserActivityQuickJoinReqVO;
import cn.youqu.happy.module.youqu.controller.app.userActivity.vo.AppUserActivityUpdateReqVO;
import cn.youqu.happy.module.youqu.convert.userActivity.UserActivityConvert;
import cn.youqu.happy.module.youqu.convert.userArrange.UserArrangeConvert;
import cn.youqu.happy.module.youqu.dal.dataobject.systemActivity.SystemActivityDO;
import cn.youqu.happy.module.youqu.dal.dataobject.userActivity.UserActivityDO;
import cn.youqu.happy.module.youqu.dal.dataobject.userBlack.UserBlackDO;
import cn.youqu.happy.module.youqu.dal.dataobject.userJoinActivity.UserJoinActivityDO;
import cn.youqu.happy.module.youqu.dal.mysql.userActivity.UserActivityMapper;
import cn.youqu.happy.module.youqu.enums.userActivity.UserActivityStatusEnum;
import cn.youqu.happy.module.youqu.enums.userArrange.UserArrangeStatusEnum;
import cn.youqu.happy.module.youqu.enums.userBalck.UserBlackTypeEnum;
import cn.youqu.happy.module.youqu.service.arrangeEdit.ArrangeEditService;
import cn.youqu.happy.module.youqu.service.systemActivity.SystemActivityService;
import cn.youqu.happy.module.youqu.service.userArrange.UserArrangeService;
import cn.youqu.happy.module.youqu.service.userBlack.UserBlackService;
import cn.youqu.happy.module.youqu.service.userJoinActivity.UserJoinActivityService;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

import static cn.youqu.happy.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.youqu.happy.module.member.enums.ErrorCodeConstants.USER_NOT_EXISTS;
import static cn.youqu.happy.module.youqu.enums.ErrorCodeConstants.*;

/**
 * 用户发起活动 Service 实现类
 *
 * @author 王其岩 20112001045
 */
@Service
@Validated
public class UserActivityServiceImpl implements UserActivityService {

    @Resource
    private UserActivityMapper userActivityMapper;

    @Resource
    private SystemActivityService systemActivityService;

    @Resource
    @Lazy
    private MemberUserService memberUserService;

    @Resource
    @Lazy
    private UserArrangeService userArrangeService;

    @Resource
    @Lazy
    private UserBlackService userBlackService;

    @Resource
    @Lazy
    private UserJoinActivityService userJoinActivityService;

    /**
     * 每5分钟自动更新一次互动状态
     */
    private static final long SCHEDULER_PERIOD = 5 * 60 * 1000L;

    @Override
    public Integer createUserActivity(UserActivityCreateReqVO createReqVO) {
        // 插入
        UserActivityDO userActivity = UserActivityConvert.INSTANCE.convert(createReqVO);
        userActivityMapper.insert(userActivity);
        // 返回
        return userActivity.getId();
    }

    @Override
    public void updateUserActivity(UserActivityUpdateReqVO updateReqVO) {
        // 校验存在
        this.validateUserActivityExists(updateReqVO.getId());
        // 更新
        UserActivityDO updateObj = UserActivityConvert.INSTANCE.convert(updateReqVO);
        userActivityMapper.updateById(updateObj);
    }

    @Override
    public void deleteUserActivity(Integer id) {
        // 校验存在
        this.validateUserActivityExists(id);
        // 删除
        userActivityMapper.deleteById(id);
    }

    private void validateUserActivityExists(Integer id) {
        if (userActivityMapper.selectById(id) == null) {
            throw exception(USER_ACTIVITY_NOT_EXISTS);
        }
    }

    @Override
    public UserActivityDO getUserActivity(Integer id) {
        return userActivityMapper.selectById(id);
    }

    @Override
    public List<UserActivityDO> getUserActivityList(Collection<Integer> ids) {
        return userActivityMapper.selectBatchIds(ids);
    }

    @Override
    public List<UserActivityDO> getUserActivityList(Collection<Integer> ids, Long uid) {
        List<UserActivityDO> userActivityDOS = userActivityMapper.selectBatchIds(ids);
        //筛选用户可见的活动
        return filterUserCanSeeUserActivity(userActivityDOS, uid);
    }

    @Override
    public PageResult<UserActivityDO> getUserActivityPage(UserActivityPageReqVO pageReqVO) {
        return userActivityMapper.selectPage(pageReqVO);
    }

    @Override
    public PageResult<UserActivityDO> getUserActivityPage(UserActivityPageReqVO pageReqVO, Long uid) {
        PageResult<UserActivityDO> userActivityDOPageResult = userActivityMapper.selectPage(pageReqVO);
        List<UserActivityDO> list = userActivityDOPageResult.getList();
        //筛选用户可见的活动
        List<UserActivityDO> userActivityDOS = filterUserCanSeeUserActivity(list, uid);
        userActivityDOPageResult.setList(userActivityDOS);
        userActivityDOPageResult.setTotal((long) userActivityDOS.size());
        return userActivityDOPageResult;
    }

    @Override
    public List<UserActivityDO> getUserActivityList(UserActivityExportReqVO exportReqVO) {

        return userActivityMapper.selectList(exportReqVO);
    }

    @Override
    public Integer publishUserActivity(AppUserActivityCreateReqVO createReqVO, Long uid) {

        //1.先校验活动是否存在

        SystemActivityDO activity = systemActivityService.getSystemActivity(createReqVO.getActivityId());
        if (activity == null) {
            throw exception(SYSTEM_ACTIVITY_NOT_EXISTS);
        }
        //2 判断时间 是否合法
        if (createReqVO.getAppointTime().compareTo(new Date()) < 0 || createReqVO.getEndTime().compareTo(createReqVO.getAppointTime()) < 0) {
            throw exception(USER_ACTIVITY_TIME_NOT_AVAILABLE);
        }
        //3 设置活动默认值
        if (createReqVO.getActivityName() == null) {
            createReqVO.setActivityName(activity.getActivityName());
        }
        if (createReqVO.getMaxPartners() == null) {
            createReqVO.setMaxPartners(activity.getMaxPartners());
        }
        if (createReqVO.getMinPartners() == null) {
            createReqVO.setMinPartners(activity.getMinPartners());
        }


        UserActivityDO userActivityDO = UserActivityConvert.INSTANCE.convert(createReqVO, uid);
        //将自己加入战队
        userActivityDO.setPartners(String.valueOf(uid));
        userActivityDO.setCurrentPartners(1);
        userActivityMapper.insert(userActivityDO);
        //必须在插入之后才能获取活动id
        userJoinActivityService.joinUserActivity(userActivityDO.getId(), userActivityDO.getUid(), uid);

        return userActivityDO.getId();
    }

    @Override
    public void updateUserActivity(AppUserActivityUpdateReqVO updateReqVO, Long uid) {
        //1. 判断是否属于该用户
        UserActivityDO activityDO = userActivityMapper.findOneByUidAndId(uid, updateReqVO.getId());
        if (activityDO == null) {
            throw exception(USER_ACTIVITY_NOT_EXISTS);
        }
        //2 判断时间 是否合法
        if (updateReqVO.getAppointTime() != null) {
            if (updateReqVO.getAppointTime().compareTo(new Date()) < 0) {
                throw exception(USER_ACTIVITY_TIME_NOT_AVAILABLE);
            }
        }
        if (updateReqVO.getEndTime() != null) {
            if (updateReqVO.getEndTime().compareTo(new Date()) < 0) {
                throw exception(USER_ACTIVITY_TIME_NOT_AVAILABLE);
            }
        }
        if (updateReqVO.getAppointTime() != null && updateReqVO.getEndTime() != null) {
            if (updateReqVO.getEndTime().compareTo(updateReqVO.getAppointTime()) < 0) {
                throw exception(USER_ACTIVITY_TIME_NOT_AVAILABLE);
            }
        }

        UserActivityDO updateObj = UserActivityConvert.INSTANCE.convert(updateReqVO, uid);
        userActivityMapper.updateById(updateObj);
    }

    /**
     * 组队成功的要在活动编辑内申请编辑{@link ArrangeEditService}fun:createArrangeEdit
     *
     * @param id
     * @param uid
     * @return
     */
    @Override
    public boolean cancelUserActivity(Integer id, Long uid) {
        //1. 判断是否属于该用户
        UserActivityDO activityDO = userActivityMapper.findOneByUidAndId(uid, id);
        if (activityDO == null) {
            throw exception(USER_ACTIVITY_NOT_EXISTS);
        }
        //已取消
        if (Objects.equals(activityDO.getActivityStatus(), UserActivityStatusEnum.ACTIVITY_CANCEL.getStatus())) {
            throw exception(USER_ACTIVITY_ALREADY_CANCEL);
        }
        //活动中不可取消
        if (Objects.equals(activityDO.getActivityStatus(), UserActivityStatusEnum.ACTIVITY_ING.getStatus())) {
            throw exception(USER_ACTIVITY_ALREADY_ING);
        }
        //活动结束不可取消
        if (Objects.equals(activityDO.getActivityStatus(), UserActivityStatusEnum.ACTIVITY_END.getStatus())) {
            throw exception(USER_ACTIVITY_ALREADY_END);
        }
        //2 判断 活动是否组队成功
        if (Objects.equals(activityDO.getActivityStatus(), UserActivityStatusEnum.ACTIVITY_TEAM_ING.getStatus()) || (
                !Objects.equals(activityDO.getActivityStatus(), UserActivityStatusEnum.ACTIVITY_TEAM_FAIL.getStatus()) &&
                        !Objects.equals(activityDO.getActivityStatus(), UserActivityStatusEnum.ACTIVITY_TEAM_SUCCESS.getStatus()) &&
                        !Objects.equals(activityDO.getActivityStatus(), UserActivityStatusEnum.ACTIVITY_WAITING.getStatus()) &&
                        !Objects.equals(activityDO.getActivityStatus(), UserActivityStatusEnum.ACTIVITY_ING.getStatus()) &&
                        !Objects.equals(activityDO.getActivityStatus(), UserActivityStatusEnum.ACTIVITY_CANCEL.getStatus()))
        ) {
            //组队中 组队失败 直接取消
            return userActivityMapper.updateActivityStatusAndRemarkById(UserActivityStatusEnum.ACTIVITY_CANCEL.getStatus(), "用户取消组队", id) > 0;
        } else {//组队成功 or 组队结束
            //取消需经过队友同意
            //发起一个安排编辑申请
            throw exception(USER_ACTIVITY_ALREADY_TEAMED);
        }
//        return false;
    }

    @Override
    public boolean forceCancelUserActivity(Integer id, String reason, Long userId) {
        UserActivityDO activityDO = userActivityMapper.findOneByUidAndId(userId, id);
        if (activityDO == null) {
            throw exception(USER_ACTIVITY_NOT_EXISTS);
        }
        //组队中
        if (Objects.equals(activityDO.getActivityStatus(), UserActivityStatusEnum.ACTIVITY_TEAM_ING.getStatus())) {
            //未结束
            if (new Date().compareTo(activityDO.getEndTime()) <= 0) {
                return this.forceCancelUserActivity(id, reason);
            }
        }
        return false;
    }

    private boolean forceCancelUserActivity(Integer id, String reason) {
        int i = userActivityMapper.updateActivityStatusAndRemarkById(UserActivityStatusEnum.ACTIVITY_TEAM_END.getStatus(), reason, id);
        return i > 0;
    }

    @Override
    public boolean forceSuccessUserActivity(Integer id, String reason, Long userId) {
        UserActivityDO activityDO = userActivityMapper.findOneByUidAndId(userId, id);
        if (activityDO == null) {
            throw exception(USER_ACTIVITY_NOT_EXISTS);
        }

        if (Objects.equals(activityDO.getActivityStatus(), UserActivityStatusEnum.ACTIVITY_TEAM_ING.getStatus())) {
            if (activityDO.getCurrentPartners() >= activityDO.getMinPartners()) {
                if (!StringUtils.hasText(reason)) {
                    reason = "队长强制组队成功";
                }
                int i = this.userActivityMapper.updateActivityStatusAndRemarkById(UserActivityStatusEnum.ACTIVITY_TEAM_SUCCESS.getStatus(), reason, id);
                //创建活动安排
                UserArrangeCreateReqVO createReqVO = UserArrangeConvert.INSTANCE.convert(activityDO);
                createReqVO.setArrangeStatus(UserArrangeStatusEnum.ARRANGE_WAITING.getStatus());
                createReqVO.setPartnerList(StrUtils.stringConvertToList(activityDO.getPartners()));
                System.out.println("activityDO.getPartners()" + activityDO.getPartners());
                userArrangeService.createUserArrange(createReqVO);
                return i > 0;
            }
        } else {
            throw exception(USER_ACTIVITY_CURRENT_STATUS_CAN_NOT_MODIFY);
        }

        //组队中
        return false;
    }

    private boolean autoCancelUserActivity(Integer id, String reason) {
        UserActivityDO activityDO = userActivityMapper.selectById(id);
        if (activityDO != null) {
            //组队中

            if (Objects.equals(activityDO.getActivityStatus(), UserActivityStatusEnum.ACTIVITY_TEAM_ING.getStatus())) {
                if (new Date().compareTo(activityDO.getEndTime()) >= 0) {
                    if (activityDO.getCurrentPartners() < activityDO.getMinPartners()) {
                        //组队失败
                        activityDO.setActivityStatus(UserActivityStatusEnum.ACTIVITY_TEAM_FAIL.getStatus());
                        activityDO.setRemark("人数不足 组队失败");
                        userActivityMapper.updateById(activityDO);
                    } else {
                        if (reason == null) reason = "截止时间已到 自动关闭组队";
                        return this.forceCancelUserActivity(id, reason);
                    }

                }
            }
        }
        return false;
    }

    //自动设置成功状态
    private boolean autoSuccessUserActivity(Integer id, String reason) {
        UserActivityDO activityDO = userActivityMapper.selectById(id);
        if (activityDO != null) {
            if (Objects.equals(activityDO.getActivityStatus(), UserActivityStatusEnum.ACTIVITY_TEAM_ING.getStatus())) {
                if (activityDO.getCurrentPartners() >= activityDO.getMaxPartners()) {
                    if (reason == null) reason = "队伍已满 组队成功";
                    int i = this.userActivityMapper.updateActivityStatusAndRemarkById(UserActivityStatusEnum.ACTIVITY_TEAM_SUCCESS.getStatus(), reason, id);
                    // 创建活动安排
                    UserArrangeCreateReqVO createReqVO = UserArrangeConvert.INSTANCE.convert(activityDO);
                    createReqVO.setArrangeStatus(UserArrangeStatusEnum.ARRANGE_WAITING.getStatus());
                    //设置参与人
                    createReqVO.setPartnerList(StrUtils.stringConvertToList(activityDO.getPartners()));
                    userArrangeService.createUserArrange(createReqVO);
                    return i > 0;
                }
            }
        }
        return false;
    }

    @Scheduled(fixedDelay = SCHEDULER_PERIOD, initialDelay = SCHEDULER_PERIOD)
    public void autoUpdateUserActivityStatus() {
        //定时更新组队活动状态
        LambdaQueryWrapperX<UserActivityDO> lambdaQueryWrapperX = new LambdaQueryWrapperX();
        lambdaQueryWrapperX.ge(UserActivityDO::getEndTime, new Date());
        lambdaQueryWrapperX.eq(UserActivityDO::getActivityStatus, UserActivityStatusEnum.ACTIVITY_TEAM_ING.getStatus());
        List<UserActivityDO> userActivityDOS = userActivityMapper.selectList(lambdaQueryWrapperX);

        userActivityDOS.forEach(item -> {
            if (item.getCurrentPartners() >= item.getMaxPartners()) {
                item.setActivityStatus(UserActivityStatusEnum.ACTIVITY_TEAM_SUCCESS.getStatus());
                item.setRemark("队伍已满 组队成功");
                // 创建活动安排
                userActivityMapper.updateById(item);
                UserArrangeCreateReqVO createReqVO = UserArrangeConvert.INSTANCE.convert(item);
                createReqVO.setArrangeStatus(UserArrangeStatusEnum.ARRANGE_WAITING.getStatus());
                createReqVO.setPartnerList(StrUtils.stringConvertToList(item.getPartners()));

                //此方法只会创建一个活动安排 如果已经创建不会再次创建
                userArrangeService.createUserArrange(createReqVO);
            } else if (item.getCurrentPartners() < item.getMinPartners()) {
                //组队失败
                item.setActivityStatus(UserActivityStatusEnum.ACTIVITY_TEAM_FAIL.getStatus());
                item.setRemark("人数不足 组队失败");
                userActivityMapper.updateById(item);
            } else {
                //达到最小 人数
                item.setActivityStatus(UserActivityStatusEnum.ACTIVITY_TEAM_END.getStatus());
                item.setRemark("时间已到 关闭组队");
                userActivityMapper.updateById(item);
                // 创建活动安排
                UserArrangeCreateReqVO createReqVO = UserArrangeConvert.INSTANCE.convert(item);
                createReqVO.setArrangeStatus(UserArrangeStatusEnum.ARRANGE_WAITING.getStatus());
                createReqVO.setPartnerList(StrUtils.stringConvertToList(item.getPartners()));

                //此方法只会创建一个活动安排 如果已经创建不会再次创建
            }
        });

    }

    private void validUserActivityTimeAvailable(Integer id) {
        UserActivityDO activityDO = userActivityMapper.selectById(id);
        if (activityDO != null) {
            if (Objects.equals(activityDO.getActivityStatus(), UserActivityStatusEnum.ACTIVITY_TEAM_ING.getStatus())) {
                if (new Date().compareTo(activityDO.getEndTime()) >= 0) {
                    this.forceCancelUserActivity(id, "截止时间已到 自动关闭组队");
                    throw exception(USER_ACTIVITY_TEAM_END);
                }
            }
        }
    }

    @Override
    public boolean kickPartnerUserActivity(Integer id, Long targetId, Long UserId) {
        //判断是否是自己
        if (targetId.equals(UserId)) {
            throw exception(USER_ACTIVITY_CAN_NOT_KICK_YOURSELF);
        }
        //1. 判断是否属于该用户
        UserActivityDO activityDO = userActivityMapper.findOneByUidAndId(UserId, id);
        if (activityDO == null) {
            throw exception(USER_ACTIVITY_NOT_EXISTS);
        }
        if (!Objects.equals(activityDO.getActivityStatus(), UserActivityStatusEnum.ACTIVITY_TEAM_ING.getStatus())) {
            throw exception(USER_ACTIVITY_TEAM_END);
        }
        //验证组队时间是否在范围内
        this.validUserActivityTimeAvailable(id);

        //调用用户退出战队
        return quitUserActivity(id, targetId);

    }

    @Override
    public boolean joinUserActivity(Integer id, Long userId) {

        //1 校验 用户活动id 是否存在
        UserActivityDO activityDO = userActivityMapper.selectById(id);
        if (activityDO == null) {
            throw exception(USER_ACTIVITY_NOT_EXISTS);
        }
        //判断是否在发起人的黑名单中
        UserBlackDO userBlack = userBlackService.getUserBlack(userId, activityDO.getUid());
        if (userBlack != null) {
            if (userBlack.getBlackType().equals(UserBlackTypeEnum.ALL.getType()) ||
                    userBlack.getBlackType().equals(UserBlackTypeEnum.CAN_NOT_SEE_MY_ACTIVITY.getType())) {
                throw exception(USER_ACTIVITY_HAVE_NO_POWER_JOIN_ACTIVITY);
            }
        }
        //判断组队是否结束并自动取消
        this.autoCancelUserActivity(id, "截止时间已到 自动关闭组队");

        //2 判断是否 在组队中
        if (!Objects.equals(activityDO.getActivityStatus(), UserActivityStatusEnum.ACTIVITY_TEAM_ING.getStatus())) {
            throw exception(USER_ACTIVITY_TEAM_END);//组队已结束
        }
        //3 判断人员是否已满
        if (activityDO.getCurrentPartners() >= activityDO.getMaxPartners()) {
            throw exception(USER_ACTIVITY_TEAM_FULL);//人数已满
        }

        if (activityDO.getPartners() != null) {
            //4 判断是否已在队内
            UserJoinActivityDO userJoinActivity = userJoinActivityService.getUserJoinActivity(activityDO.getId(), activityDO.getUid(), userId);
            if (userJoinActivity != null) {
                throw exception(USER_ACTIVITY_ALREADY_JOIN_TEAM);//已经加入
            }

        }


        //加入到partner中
        // FIXME: 2022/4/16 增加用户加入活动映射表 避免并发导致用户加入活动失败
        userJoinActivityService.joinUserActivity(activityDO.getId(), activityDO.getUid(), userId);
        List<Long> userActivityPartners = userJoinActivityService.getUserActivityPartners(activityDO.getId(), activityDO.getUid());
        activityDO.setPartners(ArrayUtils.listConvertToString2(userActivityPartners));
        activityDO.setCurrentPartners(userActivityPartners.size());

        //更新
        int i = userActivityMapper.updateById(activityDO);

        // 判断是否队满 自动成功
        this.autoSuccessUserActivity(id, "队伍已满 组队成功");
        return i > 0;
    }

    @Override
    public boolean quitUserActivity(Integer id, Long userId) {

        //1 校验 用户活动id 是否存在
        UserActivityDO activityDO = userActivityMapper.selectById(id);
        if (activityDO == null) {
            throw exception(USER_ACTIVITY_NOT_EXISTS);
        }
        //判断是否是自己创建的队伍
        if (userId.equals(activityDO.getUid())) {

            throw exception(USER_ACTIVITY_CAN_NOT_KICK_YOURSELF);
        }
        //2 判断是否 在组队中
        if (!Objects.equals(activityDO.getActivityStatus(), UserActivityStatusEnum.ACTIVITY_TEAM_ING.getStatus())) {
            throw exception(USER_ACTIVITY_TEAM_END);//组队已结束
        }
        // 校验用户是否存在
        MemberUserDO user = memberUserService.getUser(userId);
        if (user == null) {
            throw exception(USER_NOT_EXISTS);
        }

        //3 判断是否在队内
        if (activityDO.getPartners() != null) {
            List<String> partnerArr1 = StrUtils.stringConvertToList(activityDO.getPartners());
            if (partnerArr1.stream().anyMatch(item -> item.equals(String.valueOf(userId)))) {
                //在partners 中删除
                // FIXME: 2022/4/16 修复用户并发导致退出失败
                userJoinActivityService.quitUserActivity(activityDO.getId(), activityDO.getUid(), userId);
                List<Long> userActivityPartners = userJoinActivityService.getUserActivityPartners(activityDO.getId(), activityDO.getUid());
                activityDO.setPartners(ArrayUtils.listConvertToString2(userActivityPartners));
                activityDO.setCurrentPartners(userActivityPartners.size());

                //更新
                return userActivityMapper.updateById(activityDO) > 0;
            } else {
                throw exception(USER_ACTIVITY_NOT_IN_TEAM);
            }
        } else {
            throw exception(USER_ACTIVITY_NOT_IN_TEAM);
        }
    }

    /**
     * 筛选不在对于中的
     *
     * @param userActivityDOs
     * @param uid
     * @return
     */
    private List<UserActivityDO> filterNotInUserActivity(List<UserActivityDO> userActivityDOs, Long uid) {
        return userActivityDOs.stream().filter(item -> {
            List<String> partnerArr = StrUtils.stringConvertToList(item.getPartners());
            return partnerArr.stream().noneMatch(partnerItem -> String.valueOf(uid).equals(partnerItem));
        }).collect(Collectors.toList());

    }

    /**
     * 筛选出用户可见的活动 拉黑的用户不可见
     *
     * @param userActivityDOs
     * @param uid
     * @return
     */
    private List<UserActivityDO> filterUserCanSeeUserActivity(List<UserActivityDO> userActivityDOs, Long uid) {
        List<UserBlackDO> userBlackList = userBlackService.getUserBlackList(uid);
        boolean notHaveBlack;

        Map<Long, UserBlackDO> userBackMap = new HashMap();
        if (userBlackList != null) {
            userBlackList.forEach(item -> userBackMap.put(item.getUid(), item));
            notHaveBlack = false;
        } else {
            notHaveBlack = true;
        }

        return userActivityDOs.stream().filter(item -> {
            //自己发布的一定可见
            if (Objects.equals(item.getUid(), uid)) {
                return true;
            }
            if (notHaveBlack) return true;
            UserBlackDO userBlackDO = userBackMap.get(item);
            if (userBlackDO != null) {//被此人拉黑
                return !Objects.equals(userBlackDO.getBlackType(), UserBlackTypeEnum.ALL.getType()) &&
                        !Objects.equals(userBlackDO.getBlackType(), UserBlackTypeEnum.CAN_NOT_SEE_MY_ACTIVITY.getType());
            }
            return true;
        }).collect(Collectors.toList());

    }

    @Override
    public Integer quickJoinUserActivity(AppUserActivityQuickJoinReqVO quickJoinReqVO, Long userId) {
        //查找 组队中的用户活动 活动id在范围内 人数未满

        List<UserActivityDO> userActivityDOS = userActivityMapper.selectQuickJoinList(quickJoinReqVO.getActivityIds());
        if (userActivityDOS == null || userActivityDOS.size() <= 0) {
            throw exception(USER_ACTIVITY_NOT_FIND_RELEVANT_TEAM);
        }

        //筛选自己没在队伍的
        List<UserActivityDO> userActivityDOS1 = filterNotInUserActivity(userActivityDOS, userId);
        if (userActivityDOS1.size() <= 0) {
            throw exception(USER_ACTIVITY_CAN_NOT_FETCH_RELEVANT_TEAM);
        }
        //随机选择一个队伍并加入
        List<UserActivityDO> collect =
                userActivityDOS1.stream().sorted(Comparator.comparingInt(a -> (a.getMaxPartners() - a.getCurrentPartners())))
                        .collect(Collectors.toList());

        //加入战队
        joinUserActivity(collect.get(0).getId(), userId);
        return collect.get(0).getId();
    }

    @Override
    public UserActivityDO getUserActivity(Integer id, Long loginUserId) {
        return userActivityMapper.findOneByUidAndId(loginUserId, id);
    }

}
